/**
 * 
 */
package net.uman.framework.modules.orm.hibernate;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.uman.util.ApplicationProperties;

import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.support.OpenSessionInViewFilter;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * @author haocheng
 *
 */
public class OpenSingleSessionInViewFilter extends OpenSessionInViewFilter {
	
	//private static String[] writes=ApplicationProperties.getValue("db.write.only").split(",");
	private static String[] writes={"save","add","create","update","delete"};
	private String readOnly= DEFAULT_SESSION_FACTORY_BEAN_NAME;
	private String writeOnly= DEFAULT_SESSION_FACTORY_BEAN_NAME;

	protected String getSessionFactoryBeanName(HttpServletRequest request) {
		 if(isWrite(request)){
			 return getWriteOnly();
		 }else{
			 return getReadOnly();
		 }
	}

	private boolean isWrite(HttpServletRequest request) {
		//String servletPath=request.getServletPath();
		String servletPath=request.getPathInfo();
		if(servletPath==null || servletPath.equals("")){
			servletPath=request.getServletPath();
		}
		assert servletPath==null ||servletPath=="":"servletPath 不应该为空！";
		String action=servletPath.substring(servletPath.lastIndexOf("/"));
		assert action==null ||action=="":"action 不应该为空！";
		for(String write:writes){
			if(action.contains(write)){
				return true;
			}
		}
		return false;
	}

	@Override
	protected SessionFactory lookupSessionFactory(HttpServletRequest request) {
		if (logger.isDebugEnabled()) {
			logger.debug("Using SessionFactory '" + getSessionFactoryBeanName() + "' for OpenSessionInViewFilter");
		}
		WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
		return wac.getBean(getSessionFactoryBeanName(request), SessionFactory.class);
	}

	@Override
	protected void doFilterInternal(HttpServletRequest request,
			HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		if(filterSession(request)){
			filterChain.doFilter(request, response);
		}
		super.doFilterInternal(request, response, filterChain);
	}

	private boolean filterSession(HttpServletRequest request) {
		return false;
	}

	public String getWriteOnly() {
		return writeOnly;
	}

	public void setWriteOnly(String writeOnly) {
		this.writeOnly = writeOnly;
	}

	public String getReadOnly() {
		return readOnly;
	}

	public void setReadOnly(String readOnly) {
		this.readOnly = readOnly;
	}
}
